// 权限组件
<template>
  <div class="power_component">
    <!-- 管理成员 -->

    <div class="title_box">
      <div>{{ $t('teamDoc.people.member') }}</div>
      <div class="title_right">
        <!-- <el-button  type="text" @click="onSynchronization" :disabled="jdt"> 同步所有下级权限 </el-button> -->
        <el-button v-if="multipleSelection.length != 0" type="text" style="margin-left:12px;"
          @click="bulkEditingClick">{{ $t('teamDoc.people.roleBat') }}</el-button>

        <el-button v-if="multipleSelection.length != 0" type="text" style="color:#F56C6C;margin-right:10px"
          @click="deleteUserClick(multipleSelection)">
          {{ $t('teamDoc.people.delBat') }}
        </el-button>
        <div class="title1" @click="openDeptUserClick" v-if="!isCreatePeopleBtn">
          <el-icon>
            <Plus />
          </el-icon>
          {{ $t('teamDoc.people.manageMembers') }}
        </div>
      </div>
    </div>

    <!-- 搜索条件 -->
    <div class="power_component_search">
      <el-input v-model="searchInput" width="200" placeholder="搜索成员" clearable @keyup.enter="searchName" />
      <el-popover ref="sortPopoverRefs" placement="bottom" title="" width="160" trigger="click">
        <div class="people_box">
          <el-checkbox-group v-model="memberCheckList" @change="memberCheckChange">
            <el-checkbox  v-for="(item, index) in peopleRoleList" :key="index" :label="item.id" :value="item.id" style="display: block">
              <svg-icon icon-class="role2" :style="{ color: item.iconColor ? item.iconColor : '#000000' }" />
              {{ item.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <template #reference>
          <span><i style="font-size: 12px" class="iconfont-el icon-arrow-down"></i> 权限</span>
        </template>
      </el-popover>
      <el-popover ref="sortPopoverRefs" placement="bottom" title="" width="160" trigger="click">
        <div class="deptBox">
          <el-checkbox-group v-model="dimensionalityCheckList" @change="memberCheckChange">
            <el-checkbox  v-for="(item, index) in dimensionalityList" :key="index" :value="item.value" :label="item.value">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <template #reference>
          <span> <i style="font-size: 12px" class="iconfont-el icon-arrow-down"></i> 维度</span>
        </template>
      </el-popover>
    </div>
    <!-- 表格 -->
    <el-table :data="TableDataList" style="width: 100%" height="300px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="35" :selectable="selectableFunc"> </el-table-column>
      <el-table-column :label="$t('teamDoc.people.name')" width="250">
        <template #default="scope">
          <div class="table_NameBox">
            <!-- <img v-if="scope.row.objectType == '3'" style="background: #3662EC;" src="@/assets/images/jues.png" alt="" />
                  <img v-if="scope.row.objectType == '2'" style="background: #FE4D4F;" src="@/assets/images/gwei.png" alt="" />
                  <img v-if="scope.row.objectType == '1'" style="background: #07b9b9;" src="@/assets/images/bumeng.png" alt="" /> -->
            <div class="avatar" v-if="scope.row.objectType == '0'">
              <div>{{ scope.row.objectName.slice(0, 1) }}</div>
            </div>
            <div class="table_Name">
              <p>{{ scope.row.objectName }}</p>
              <span v-if="scope.row.isExtend !== undefined && scope.row.isExtend == 0 && scope.row.roleRank != 1">由【{{
                scope.row.creator }}】添加</span>
              <span v-if="scope.row.isExtend !== undefined && scope.row.isExtend == 1">继承权限</span>
            </div>
            <div class="table_Name">
              <span v-show="scope.row.roleRank == 1" class="table_Name_syz">所有者</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="objectTypeText" :label="$t('teamDoc.people.dimensionality')" width="60">
        <template #default="scope">{{ scope.row.objectTypeText }}</template>
      </el-table-column>
      <el-table-column :label="$t('teamDoc.people.jurisdiction')">
        <template #default="scope">
          <div class="temp_box">
            <div class="role_box">
              <span class="role_name" :class="[scope.row.roleRank == 1 ? 'diabledsBtn' : '']"
                @click="openSelectRoleTeamClick(scope.row)">
                {{ scope.row.roleName }}
                <el-icon>
                  <ArrowRight />
                </el-icon>
              </span>
            </div>
            <!-- && !(roleData.rank > scope.row.roleRank) -->
            <div class="icon_box" v-if="scope.row.roleRank != 1" @click="deleteUserClick([scope.row])">
              <el-icon>
                <Close />
              </el-icon>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination @size-change="getSizeChange" @current-change="getPageChange" :current-page="commonParams.page"
      :page-sizes="[10, 20, 30, 40]" :page-size="commonParams.size" layout="total, prev, pager, next, sizes"
      :total="commonParams.total" />
  </div>
  <div v-if="props.pageType == 'teamPeople'">
    <manageMembers ref="YuSelectPeopleNewEnterpriseRefs" @onRefresh="refreshData" />
  </div>
  <div v-if="props.pageType == 'team'">
    <teamfile-new-user ref="TeamfileSelectUserRefs" @confirmClick="teamfileSelectUser_confirmClick"></teamfile-new-user>
  </div>
  <selectRoleListTeam ref="selectRoleTeamRefs" :pageType="props.pageType" @RowClick="selectRoleTeamRowClick" />

</template>
<script setup lang="ts">
// 自定义组件
import manageMembers from './manageMembers.vue'
import selectRoleListTeam from './select-role-list-team.vue'
import teamfileNewUser from './teamfile-new-user.vue'
// 接口
import teamRoleApi from '@/api/teamKnowdge/teamRoleApi'
import teamFileApi from '@/api/teamKnowdge/teamFileApi'
import { apiTeamMemberQuery, apiTeamMemberDelete, apiTeamRelevanceRoleDelete, apiTeamRelevanceRoleAdd } from '@/api/teamKnowdge/teamDocApi'
import { ref, reactive } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
// import  roleList_team  from '@/utils/roleList'
const props = defineProps({
  treeNodeId: {
    type: Number,
    default: 0
  },
  createBy: {
    type: String,
    default: ''
  },
  pageType: {
    type: String,
    default: ""
  }
})
const { proxy } = getCurrentInstance() as any
import { useTeamRoleStore } from '@/store/modules/teamRole'
import { apiTeamMemberUpdateUserRoleType, apiTeamRelevanceRoleUpdateUserRoleType } from '@/api/teamKnowdge/teamDocApi'
const teamRoleStore = useTeamRoleStore()
const roleData = teamRoleStore.roleData
const route = useRoute()
const nickname = ref<string>('')
const YuSelectPeopleNewEnterpriseRefs = ref<any>(null)
const roleList = ref<any[]>([]) // 权限筛选列表
const memberCheckList = ref<string[]>([]) // 权限筛选选择值
const peopleRoleList = ref<any[]>([]) // 人员角色列表
const dimensionalityList = ref<any[]>([
  { value: '0', label: '用户' },
  { value: '1', label: '部门' },
  { value: '2', label: '角色' },
  { value: '3', label: '岗位' }
]) // 维度筛选列表
const dimensionalityCheckList = ref<string[]>([]) // 维度筛选选择值
const TableDataList = ref<any[]>([]) // 表格数据
const multipleSelection = ref<any[]>([]) // 表格选中数据
const teamId = ref(null)
const roleLoading = ref(false)
const searchInput = ref<string>('')
const selectRoleTeamRefs = ref<any>(null)
const TeamfileSelectUserRefs = ref<any>(null)
const rowFileInfo = ref({
  id: null
})
const commonParams = reactive({
  page: 1,
  size: 10,
  total: 0
})
onMounted(() => {
  getRoleList()
  getTableData(route.query.teamId)
})
const isCreatePeopleBtn = computed(() => {
  if (props.pageType == 'team') {
    return !proxy.$yuUtils.documentsPermissionFunc(["jurisdiction"], teamRoleStore.myTeamFileRoleList)
  }
  if (props.pageType == 'teamPeople') { }
  return !proxy.$yuUtils.documentsPermissionFunc(["jurisdiction"], teamRoleStore.myRoleList)
})

const refreshData = () => {
  getTableData(route.query.teamId)
}
const searchName = (e) => {
  nickname.value = e.target.value
  getTableData(route.query.teamId)
}
// 分页
const getSizeChange = (size: number) => {
  commonParams.size = size
  getTableData(route.query.teamId)
}
// 页码
const getPageChange = (page: number) => {
  commonParams.page = page
  getTableData(route.query.teamId)
}

const getRoleList = () => {
  roleLoading.value = true
  teamRoleApi
    .apiTeamRoleQuery({
      teamId: route.query.teamId,
      page: 0,
      size: 9999
    })
    .then((res) => {
      peopleRoleList.value = res.data.rows
      roleLoading.value = false
    })
    .catch((err) => {
      roleLoading.value = false
    })
}
// 获取表格数据
const getTableData = async (id?, row?) => {
  // console.log(row, 'row')
  if (id) {
    teamId.value = id
  }
  if (row) {
    rowFileInfo.value = row
  }
  let res = null
  let params: { page: number; size: number; sort: string; objectType: string[]; roleId: string[]; NickName?: string } = {
    page: commonParams.page - 1,
    size: commonParams.size,
    sort: "id,asc",
    objectType: dimensionalityCheckList.value,
    roleId: memberCheckList.value,
  }
  if (searchInput.value) {
    params.NickName = searchInput.value
  }
  if (props.pageType == 'teamPeople') {
    res = await apiTeamMemberQuery({
      ...params,
      teamId: teamId.value
    })
  }
  if (props.pageType == 'team') {
    res = await teamFileApi.apiTeamRelevanceRoleQuery({
      treeNodeId: rowFileInfo.value.id,
      ...params
    })
  }
  TableDataList.value = res.data.rows
  TableDataList.value = TableDataList.value.map((item: any) => {
    let objectTypeText
    switch (item.objectType) {
      case 0:
        objectTypeText = "用户"
        break
      case 1:
        objectTypeText = "部门"
        break
      case 2:
        objectTypeText = "岗位"
        break
      case 3:
        objectTypeText = "角色"
        break
      default:
        objectTypeText = "未知"
    }
    // 将新属性添加到对象中
    item.objectTypeText = objectTypeText
    return item
  })
  commonParams.total = res.data.total
}
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}
const selectableFunc = (row: any, index: number) => {
  if (row.roleRank != 1) {
    return true
  }
}
const teamfileSelectUser_confirmClick = async (val) => {
  TableDataList.value = []

  let teamArr = val.map((item) => {
    return {
      teamId: route.query.teamId,
      // roleType: item.roleType ? item.roleType : "3",
      roleId: item.id,
      objectId: item.objectId,
      objectType: item.objectType,
      treeNodeId: rowFileInfo.value.id
    }
  })
  const res = await apiTeamRelevanceRoleAdd(teamArr)
  if (res.code == 200) {
    ElMessage.success('操作成功')
    getTableData(route.query.teamId)
  } else {
    ElMessage.error(res.msg)
  }

}
// 权限筛选
const memberCheckChange = () => {
  commonParams.page = 1
  getTableData(route.query.teamId)
}
// 权限弹窗
const openSelectRoleTeamClick = async (row) => {
  if (roleData.rank > row.roleRank) {
    return
  }
  if (row.roleRank == 1) {
    return
  }
  await selectRoleTeamRefs.value.getTableData(row)

}
// 选择权限
const selectRoleTeamRowClick = async (row, val) => {
  let res = null
  try {

    if (props.pageType == "teamPeople") {
      //团队
      let params = val.map((item) => {
        return {
          id: item.id,
          teamId: teamId.value,
          roleId: row.id,
          objectId: item.objectId,
          objectType: item.objectType
        }
      })
      res = await apiTeamMemberUpdateUserRoleType(params)
    }
    if (props.pageType == "team") {
      //团队文件
      val.forEach((item) => {
        item.roleId = row.id
      })
      console.log(val,'val')
      res = await apiTeamRelevanceRoleUpdateUserRoleType(val)
    }
    ElMessage.success('操作成功')
    getTableData(route.query.teamId)
  } catch (error) {

  }
}
// 修改权限 
const bulkEditingClick = () => {

}
const openDeptUserClick = () => {
  let element = null
  if (props.pageType == 'teamPeople') {
    element = YuSelectPeopleNewEnterpriseRefs.value
    element.addClick()
  }
  if (props.pageType == 'team') {
    element = TeamfileSelectUserRefs.value
    element.getTableData()
    element.getRightUserList(rowFileInfo.value.id)
  }
}

// 权限权限
const deleteUserClick = (row: any) => {
  if (props.pageType == 'teamPeople') {
    ElMessageBox.confirm(`此操作将删除成员数据, 是否继续?`, '提示', { type: 'warning' })
      .then(() => {
        apiTeamMemberDelete(row).then((res: any) => {
          if (res.code === 200) {
            ElMessage.success('删除成功')
            getTableData(route.query.teamId)
          }
        })
      })
      .catch(() => { })
  }
  if (props.pageType == 'team') {
    ElMessageBox.confirm(`此操作将删除成员数据, 是否继续?`, '提示', { type: 'warning' })
      .then(() => {
        apiTeamRelevanceRoleDelete(row).then((res: any) => {
          if (res.code === 200) {
            ElMessage.success('删除成功')
            getTableData(route.query.teamId)
          }
        })
      })
      .catch(() => { })
  }

}
defineExpose({
  getTableData
})
</script>
<style scoped lang="scss">
p {
  margin: 0;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
}

.power_component {
  height: 100%;
  display: flex;
  flex-direction: column;

  .title_box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #666666;
    font-size: 14px;
    margin-bottom: 20px;

    .title_right {
      display: flex;
      align-items: center;
    }

    .title1 {
      cursor: pointer;
      color: #83acff;
    }

    .mr-8 {
      margin-right: 8px;
    }
  }

  .power_component_search {
    display: flex;
    align-items: center;

    .el-tooltip__trigger {
      cursor: pointer;
      width: 60px;
      height: 30px;
      text-align: center;
      line-height: 30px;
      border-radius: 4px;

      &:hover {
        color: #409eff;
        background-color: rgba(#63affa, 0.1);
      }
    }

    .el-input {
      width: 300px;
      margin-right: 20px;
    }
  }

  .el-table {
    flex: 1;
    margin-top: 10px;
  }

  .el-pagination {
    margin-top: 10px;
  }
}

.table_NameBox {
  display: flex;
  align-items: center;

  .avatar {
    width: 24px;
    height: 24px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 12px;
    background-color: #56abfb;
    margin-right: 4px;

    div {
      margin-top: 2px;
      margin-left: 1px;
      // transform: scale(0.9, 0.9);
    }
  }

  img {
    padding: 2px;
    width: 22px;
    height: 22px;
    margin-right: 5px;
    border-radius: 15px;
  }

  .table_Name {
    margin-left: 5px;

    p {
      margin: 0;
    }

    span {
      color: #999;
    }

    .table_Name_span {
      color: black;
    }

    .table_Name_syz {
      border: 1px solid #83acff;
      padding: 1px 5px;
      border-radius: 5px;
      margin-left: 5px;
      color: #83acff;
    }
  }
}

.temp_box {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .role_box {
    width: 100%;

    :deep(.el-input__inner) {
      width: 100px;
      border: 0;
    }

    .role_name {
      cursor: pointer;
    }

    .diabledsBtn {
      color: #bbbfc4;
      cursor: no-drop !important;
    }

    .all_role_text {
      margin-left: 15px;
      color: #bbbfc4;
      font-size: 13px;
    }
  }

  .icon_box {
    font-size: 16px;
    cursor: pointer;
    visibility: hidden;

    :hover {
      color: #f56c6c;
    }
  }
}

.el-select-dropdown__item {
  height: auto;

  p {
    margin: 0;
  }

  line-height: 20px;
}

.role_item_box {
  padding: 10px 0;

  .name {
    display: flex;
    justify-content: space-between;
    font-weight: bold;
  }

  .describe {
    font-size: 11px;
  }
}

:deep(.el-table__body tr:hover .icon_box) {
  visibility: visible;
}
</style>
